package com.f9miao.starter.oss;

import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import io.minio.policy.PolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties({MinioProperties.class})
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(MinioAutoConfiguration.class);

    @Bean
    @ConditionalOnProperty(prefix = "oss.minio", value = "enable", havingValue = "true")
    public MinioClient minioClient(MinioProperties minioProperties) throws InvalidPortException, InvalidEndpointException {
        MinioClient client;
        logger.info("Using minio as oss server");
        client = new MinioClient(minioProperties.getHost(), minioProperties.getAccessKey(), minioProperties.getSecretKey());
        initBucket(client, minioProperties);
        return client;
    }

    /**
     * {@link MinioProperties#getBuckets()}<br/>
     * 创建配置文件中给出的存储桶 <br/>
     */
    protected void initBucket(MinioClient minioClient, MinioProperties minioProperties) {
        try {
            for(String bucket : minioProperties.getBuckets()){
                boolean exists = minioClient.bucketExists(bucket);
                if (!exists) {
                    logger.info(String.format("bucket %s is not exist before, create now!", bucket));
                    minioClient.makeBucket(bucket);
                    minioClient.setBucketPolicy(bucket, "*", PolicyType.READ_ONLY);
                }
            }
        } catch (Exception e) {
            logger.error("error in initiating buckets");
        }
        logger.info("bucket initiating completed");
    }

}
